<template>
  <div class="project-planning">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><Calendar /></el-icon>
          项目计划
        </h1>
        <div class="header-actions">
          <el-button @click="exportPlan">
            <el-icon><Download /></el-icon>
            导出计划
          </el-button>
          <el-button type="primary" @click="savePlan">
            <el-icon><Check /></el-icon>
            保存计划
          </el-button>
        </div>
      </div>
    </div>

    <!-- 项目信息卡片 -->
    <el-card class="project-info-card">
      <div class="project-info">
        <div class="info-item">
          <span class="label">项目名称：</span>
          <span class="value">{{ projectInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">项目经理：</span>
          <span class="value">{{ projectInfo.manager }}</span>
        </div>
        <div class="info-item">
          <span class="label">计划周期：</span>
          <span class="value">{{ projectInfo.startDate }} 至 {{ projectInfo.endDate }}</span>
        </div>
        <div class="info-item">
          <span class="label">项目状态：</span>
          <el-tag :type="getStatusType(projectInfo.status)">{{ projectInfo.status }}</el-tag>
        </div>
      </div>
    </el-card>

    <!-- 功能标签页 -->
    <el-card class="main-content">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- WBS工作分解 -->
        <el-tab-pane label="WBS工作分解" name="wbs">
          <div class="wbs-container">
            <div class="wbs-toolbar">
              <el-button type="primary" @click="addWbsItem">
                <el-icon><Plus /></el-icon>
                添加任务
              </el-button>
              <el-button @click="expandAll">
                <el-icon><ArrowDown /></el-icon>
                展开全部
              </el-button>
              <el-button @click="collapseAll">
                <el-icon><ArrowUp /></el-icon>
                收起全部
              </el-button>
              <div class="toolbar-right">
                <el-input
                  v-model="wbsSearchText"
                  placeholder="搜索任务"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
            
            <el-table
              ref="wbsTable"
              :data="filteredWbsData"
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              border
              style="width: 100%"
              :default-expand-all="false"
            >
              <el-table-column prop="name" label="任务名称" width="300">
                <template #default="{ row }">
                  <div class="task-name">
                    <el-icon v-if="row.children && row.children.length > 0"><Folder /></el-icon>
                    <el-icon v-else><Document /></el-icon>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="code" label="任务编号" width="120" />
              <el-table-column prop="duration" label="工期(天)" width="100">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.duration"
                    :min="1"
                    :max="365"
                    size="small"
                    @change="updateTaskDuration(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="startDate" label="开始日期" width="120">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.startDate"
                    type="date"
                    size="small"
                    @change="updateTaskDate(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="endDate" label="结束日期" width="120">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.endDate"
                    type="date"
                    size="small"
                    @change="updateTaskDate(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="assignee" label="负责人" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.assignee" size="small" style="width: 100%">
                    <el-option
                      v-for="user in teamMembers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="progress" label="进度" width="120">
                <template #default="{ row }">
                  <el-progress :percentage="row.progress" :stroke-width="8" />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getTaskStatusType(row.status)" size="small">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="editTask(row)">
                    编辑
                  </el-button>
                  <el-button type="success" size="small" @click="addSubTask(row)">
                    子任务
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteTask(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 甘特图 -->
        <el-tab-pane label="甘特图" name="gantt">
          <div class="gantt-container">
            <div class="gantt-toolbar">
              <el-radio-group v-model="ganttViewMode" @change="updateGanttView">
                <el-radio-button label="day">日视图</el-radio-button>
                <el-radio-button label="week">周视图</el-radio-button>
                <el-radio-button label="month">月视图</el-radio-button>
              </el-radio-group>
              <div class="toolbar-right">
                <el-button @click="zoomIn">
                  <el-icon><ZoomIn /></el-icon>
                  放大
                </el-button>
                <el-button @click="zoomOut">
                  <el-icon><ZoomOut /></el-icon>
                  缩小
                </el-button>
                <el-button @click="resetZoom">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
            </div>
            
            <!-- 甘特图表 -->
            <div ref="ganttChart" class="gantt-chart" style="height: 500px;"></div>
          </div>
        </el-tab-pane>

        <!-- 里程碑管理 -->
        <el-tab-pane label="里程碑" name="milestone">
          <div class="milestone-container">
            <div class="milestone-toolbar">
              <el-button type="primary" @click="addMilestone">
                <el-icon><Plus /></el-icon>
                添加里程碑
              </el-button>
              <el-button @click="exportMilestones">
                <el-icon><Download /></el-icon>
                导出里程碑
              </el-button>
            </div>
            
            <el-table :data="milestones" border style="width: 100%">
              <el-table-column prop="name" label="里程碑名称" width="200" />
              <el-table-column prop="description" label="描述" min-width="250" />
              <el-table-column prop="targetDate" label="目标日期" width="120">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.targetDate"
                    type="date"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="actualDate" label="实际日期" width="120">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.actualDate"
                    type="date"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getMilestoneStatusType(row.status)" size="small">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="responsible" label="负责人" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.responsible" size="small" style="width: 100%">
                    <el-option
                      v-for="user in teamMembers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="editMilestone(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteMilestone(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 依赖关系 -->
        <el-tab-pane label="任务依赖" name="dependency">
          <div class="dependency-container">
            <div class="dependency-toolbar">
              <el-button type="primary" @click="addDependency">
                <el-icon><Plus /></el-icon>
                添加依赖
              </el-button>
              <el-button @click="analyzeCriticalPath">
                <el-icon><Connection /></el-icon>
                关键路径分析
              </el-button>
            </div>
            
            <el-table :data="dependencies" border style="width: 100%">
              <el-table-column prop="predecessorName" label="前置任务" width="200" />
              <el-table-column prop="successorName" label="后续任务" width="200" />
              <el-table-column prop="type" label="依赖类型" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.type" size="small" style="width: 100%">
                    <el-option label="完成-开始" value="FS" />
                    <el-option label="开始-开始" value="SS" />
                    <el-option label="完成-完成" value="FF" />
                    <el-option label="开始-完成" value="SF" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="lag" label="滞后时间(天)" width="120">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.lag"
                    :min="0"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" min-width="200" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="danger" size="small" @click="deleteDependency(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 任务编辑对话框 -->
    <el-dialog v-model="showTaskDialog" :title="taskDialogTitle" width="600px">
      <el-form :model="currentTask" :rules="taskRules" ref="taskForm" label-width="100px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="currentTask.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务编号" prop="code">
          <el-input v-model="currentTask.code" placeholder="请输入任务编号" />
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input
            v-model="currentTask.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工期" prop="duration">
              <el-input-number
                v-model="currentTask.duration"
                :min="1"
                :max="365"
                style="width: 100%"
              >
                <template #suffix>天</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="currentTask.priority" style="width: 100%">
                <el-option label="高" value="high" />
                <el-option label="中" value="medium" />
                <el-option label="低" value="low" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="currentTask.startDate"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="currentTask.endDate"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="负责人" prop="assignee">
          <el-select v-model="currentTask.assignee" style="width: 100%">
            <el-option
              v-for="user in teamMembers"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTaskDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTask">确定</el-button>
      </template>
    </el-dialog>

    <!-- 里程碑编辑对话框 -->
    <el-dialog v-model="showMilestoneDialog" title="编辑里程碑" width="500px">
      <el-form :model="currentMilestone" ref="milestoneForm" label-width="100px">
        <el-form-item label="里程碑名称" prop="name">
          <el-input v-model="currentMilestone.name" placeholder="请输入里程碑名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="currentMilestone.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="目标日期" prop="targetDate">
          <el-date-picker
            v-model="currentMilestone.targetDate"
            type="date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-select v-model="currentMilestone.responsible" style="width: 100%">
            <el-option
              v-for="user in teamMembers"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showMilestoneDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMilestone">确定</el-button>
      </template>
    </el-dialog>

    <!-- 依赖关系对话框 -->
    <el-dialog v-model="showDependencyDialog" title="添加任务依赖" width="500px">
      <el-form :model="currentDependency" ref="dependencyForm" label-width="100px">
        <el-form-item label="前置任务" prop="predecessor">
          <el-select v-model="currentDependency.predecessor" style="width: 100%">
            <el-option
              v-for="task in flatTasks"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="后续任务" prop="successor">
          <el-select v-model="currentDependency.successor" style="width: 100%">
            <el-option
              v-for="task in flatTasks"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="依赖类型" prop="type">
          <el-select v-model="currentDependency.type" style="width: 100%">
            <el-option label="完成-开始" value="FS" />
            <el-option label="开始-开始" value="SS" />
            <el-option label="完成-完成" value="FF" />
            <el-option label="开始-完成" value="SF" />
          </el-select>
        </el-form-item>
        <el-form-item label="滞后时间">
          <el-input-number
            v-model="currentDependency.lag"
            :min="0"
            style="width: 100%"
          >
            <template #suffix>天</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            v-model="currentDependency.description"
            type="textarea"
            :rows="2"
            placeholder="请输入说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDependencyDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDependency">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {
  Calendar,
  Download,
  Check,
  Plus,
  ArrowDown,
  ArrowUp,
  Search,
  Folder,
  Document,
  ZoomIn,
  ZoomOut,
  Refresh,
  Connection
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()

// 响应式数据
const activeTab = ref('wbs')
const wbsSearchText = ref('')
const ganttViewMode = ref('week')
const showTaskDialog = ref(false)
const showMilestoneDialog = ref(false)
const showDependencyDialog = ref(false)
const taskDialogTitle = ref('添加任务')
const wbsTable = ref(null)
const ganttChart = ref(null)
const taskForm = ref(null)
const milestoneForm = ref(null)
const dependencyForm = ref(null)

// 项目信息
const projectInfo = reactive({
  name: '新产品开发项目',
  manager: '张三',
  startDate: '2024-01-01',
  endDate: '2024-06-30',
  status: '进行中'
})

// 团队成员
const teamMembers = ref([
  { id: 1, name: '张三', role: '项目经理' },
  { id: 2, name: '李四', role: '开发工程师' },
  { id: 3, name: '王五', role: '测试工程师' },
  { id: 4, name: '赵六', role: 'UI设计师' }
])

// WBS数据
const wbsData = ref([
  {
    id: 1,
    name: '需求分析阶段',
    code: 'WBS-001',
    duration: 20,
    startDate: '2024-01-01',
    endDate: '2024-01-20',
    assignee: 1,
    progress: 100,
    status: '已完成',
    children: [
      {
        id: 11,
        name: '需求调研',
        code: 'WBS-001-01',
        duration: 10,
        startDate: '2024-01-01',
        endDate: '2024-01-10',
        assignee: 1,
        progress: 100,
        status: '已完成'
      },
      {
        id: 12,
        name: '需求文档编写',
        code: 'WBS-001-02',
        duration: 10,
        startDate: '2024-01-11',
        endDate: '2024-01-20',
        assignee: 1,
        progress: 100,
        status: '已完成'
      }
    ]
  },
  {
    id: 2,
    name: '设计阶段',
    code: 'WBS-002',
    duration: 30,
    startDate: '2024-01-21',
    endDate: '2024-02-20',
    assignee: 4,
    progress: 80,
    status: '进行中',
    children: [
      {
        id: 21,
        name: '系统架构设计',
        code: 'WBS-002-01',
        duration: 15,
        startDate: '2024-01-21',
        endDate: '2024-02-05',
        assignee: 2,
        progress: 100,
        status: '已完成'
      },
      {
        id: 22,
        name: 'UI界面设计',
        code: 'WBS-002-02',
        duration: 15,
        startDate: '2024-02-06',
        endDate: '2024-02-20',
        assignee: 4,
        progress: 60,
        status: '进行中'
      }
    ]
  },
  {
    id: 3,
    name: '开发阶段',
    code: 'WBS-003',
    duration: 60,
    startDate: '2024-02-21',
    endDate: '2024-04-21',
    assignee: 2,
    progress: 30,
    status: '进行中',
    children: [
      {
        id: 31,
        name: '前端开发',
        code: 'WBS-003-01',
        duration: 30,
        startDate: '2024-02-21',
        endDate: '2024-03-22',
        assignee: 2,
        progress: 50,
        status: '进行中'
      },
      {
        id: 32,
        name: '后端开发',
        code: 'WBS-003-02',
        duration: 30,
        startDate: '2024-02-21',
        endDate: '2024-03-22',
        assignee: 2,
        progress: 40,
        status: '进行中'
      }
    ]
  }
])

// 里程碑数据
const milestones = ref([
  {
    id: 1,
    name: '需求确认',
    description: '完成需求分析和确认',
    targetDate: '2024-01-20',
    actualDate: '2024-01-20',
    status: '已完成',
    responsible: 1
  },
  {
    id: 2,
    name: '设计评审',
    description: '完成系统设计和UI设计评审',
    targetDate: '2024-02-20',
    actualDate: '',
    status: '进行中',
    responsible: 4
  },
  {
    id: 3,
    name: '开发完成',
    description: '完成所有功能开发',
    targetDate: '2024-04-21',
    actualDate: '',
    status: '未开始',
    responsible: 2
  }
])

// 依赖关系数据
const dependencies = ref([
  {
    id: 1,
    predecessor: 11,
    successor: 12,
    predecessorName: '需求调研',
    successorName: '需求文档编写',
    type: 'FS',
    lag: 0,
    description: '需求调研完成后开始文档编写'
  },
  {
    id: 2,
    predecessor: 12,
    successor: 21,
    predecessorName: '需求文档编写',
    successorName: '系统架构设计',
    type: 'FS',
    lag: 1,
    description: '需求文档完成后1天开始架构设计'
  }
])

// 当前编辑的任务
const currentTask = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  duration: 1,
  startDate: '',
  endDate: '',
  assignee: '',
  priority: 'medium',
  progress: 0,
  status: '未开始'
})

// 当前编辑的里程碑
const currentMilestone = reactive({
  id: null,
  name: '',
  description: '',
  targetDate: '',
  responsible: ''
})

// 当前编辑的依赖关系
const currentDependency = reactive({
  id: null,
  predecessor: '',
  successor: '',
  type: 'FS',
  lag: 0,
  description: ''
})

// 表单验证规则
const taskRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入任务编号', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入工期', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  assignee: [{ required: true, message: '请选择负责人', trigger: 'change' }]
}

// 计算属性
const filteredWbsData = computed(() => {
  if (!wbsSearchText.value) return wbsData.value
  
  const filterTasks = (tasks) => {
    return tasks.filter(task => {
      const matchesSearch = task.name.toLowerCase().includes(wbsSearchText.value.toLowerCase())
      if (task.children) {
        const filteredChildren = filterTasks(task.children)
        if (filteredChildren.length > 0) {
          return { ...task, children: filteredChildren }
        }
      }
      return matchesSearch
    })
  }
  
  return filterTasks(wbsData.value)
})

const flatTasks = computed(() => {
  const flatten = (tasks) => {
    let result = []
    tasks.forEach(task => {
      result.push(task)
      if (task.children) {
        result = result.concat(flatten(task.children))
      }
    })
    return result
  }
  return flatten(wbsData.value)
})

// 方法
const getStatusType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'danger'
  }
  return statusMap[status] || 'info'
}

const getTaskStatusType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'danger'
  }
  return statusMap[status] || 'info'
}

const getMilestoneStatusType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已延期': 'danger'
  }
  return statusMap[status] || 'info'
}

const addWbsItem = () => {
  taskDialogTitle.value = '添加任务'
  Object.assign(currentTask, {
    id: null,
    name: '',
    code: '',
    description: '',
    duration: 1,
    startDate: '',
    endDate: '',
    assignee: '',
    priority: 'medium',
    progress: 0,
    status: '未开始'
  })
  showTaskDialog.value = true
}

const editTask = (task) => {
  taskDialogTitle.value = '编辑任务'
  Object.assign(currentTask, { ...task })
  showTaskDialog.value = true
}

const addSubTask = (parentTask) => {
  taskDialogTitle.value = '添加子任务'
  Object.assign(currentTask, {
    id: null,
    name: '',
    code: `${parentTask.code}-${(parentTask.children?.length || 0) + 1:02d}`,
    description: '',
    duration: 1,
    startDate: parentTask.startDate,
    endDate: parentTask.endDate,
    assignee: parentTask.assignee,
    priority: 'medium',
    progress: 0,
    status: '未开始',
    parentId: parentTask.id
  })
  showTaskDialog.value = true
}

const deleteTask = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定删除任务 "${task.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API删除任务
    ElMessage.success('任务删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const saveTask = async () => {
  try {
    await taskForm.value.validate()
    
    if (currentTask.id) {
      // 编辑任务
      ElMessage.success('任务更新成功')
    } else {
      // 新增任务
      ElMessage.success('任务添加成功')
    }
    
    showTaskDialog.value = false
  } catch (error) {
    console.error('保存任务失败:', error)
  }
}

const updateTaskDuration = (task) => {
  // 根据工期更新结束日期
  if (task.startDate && task.duration) {
    const startDate = new Date(task.startDate)
    const endDate = new Date(startDate.getTime() + (task.duration - 1) * 24 * 60 * 60 * 1000)
    task.endDate = endDate.toISOString().split('T')[0]
  }
}

const updateTaskDate = (task) => {
  // 根据日期更新工期
  if (task.startDate && task.endDate) {
    const start = new Date(task.startDate)
    const end = new Date(task.endDate)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
    task.duration = diffDays
  }
}

const expandAll = () => {
  // 展开所有节点
  wbsTable.value?.store?.states?.defaultExpandAll.value = true
}

const collapseAll = () => {
  // 收起所有节点
  wbsTable.value?.store?.states?.defaultExpandAll.value = false
}

const addMilestone = () => {
  Object.assign(currentMilestone, {
    id: null,
    name: '',
    description: '',
    targetDate: '',
    responsible: ''
  })
  showMilestoneDialog.value = true
}

const editMilestone = (milestone) => {
  Object.assign(currentMilestone, { ...milestone })
  showMilestoneDialog.value = true
}

const deleteMilestone = async (milestone) => {
  try {
    await ElMessageBox.confirm(
      `确定删除里程碑 "${milestone.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = milestones.value.findIndex(m => m.id === milestone.id)
    if (index > -1) {
      milestones.value.splice(index, 1)
      ElMessage.success('里程碑删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const saveMilestone = async () => {
  try {
    if (currentMilestone.id) {
      // 编辑里程碑
      const index = milestones.value.findIndex(m => m.id === currentMilestone.id)
      if (index > -1) {
        Object.assign(milestones.value[index], { ...currentMilestone })
      }
      ElMessage.success('里程碑更新成功')
    } else {
      // 新增里程碑
      const newMilestone = {
        ...currentMilestone,
        id: Date.now(),
        status: '未开始',
        actualDate: ''
      }
      milestones.value.push(newMilestone)
      ElMessage.success('里程碑添加成功')
    }
    
    showMilestoneDialog.value = false
  } catch (error) {
    console.error('保存里程碑失败:', error)
  }
}

const addDependency = () => {
  Object.assign(currentDependency, {
    id: null,
    predecessor: '',
    successor: '',
    type: 'FS',
    lag: 0,
    description: ''
  })
  showDependencyDialog.value = true
}

const deleteDependency = async (dependency) => {
  try {
    await ElMessageBox.confirm(
      '确定删除此依赖关系吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = dependencies.value.findIndex(d => d.id === dependency.id)
    if (index > -1) {
      dependencies.value.splice(index, 1)
      ElMessage.success('依赖关系删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const saveDependency = async () => {
  try {
    if (currentDependency.predecessor === currentDependency.successor) {
      ElMessage.warning('前置任务和后续任务不能相同')
      return
    }
    
    const predecessorTask = flatTasks.value.find(t => t.id === currentDependency.predecessor)
    const successorTask = flatTasks.value.find(t => t.id === currentDependency.successor)
    
    const newDependency = {
      ...currentDependency,
      id: Date.now(),
      predecessorName: predecessorTask?.name || '',
      successorName: successorTask?.name || ''
    }
    
    dependencies.value.push(newDependency)
    ElMessage.success('依赖关系添加成功')
    showDependencyDialog.value = false
  } catch (error) {
    console.error('保存依赖关系失败:', error)
  }
}

const analyzeCriticalPath = () => {
  // 关键路径分析逻辑
  ElMessage.info('关键路径分析功能开发中...')
}

const updateGanttView = () => {
  nextTick(() => {
    initGanttChart()
  })
}

const zoomIn = () => {
  // 甘特图放大逻辑
  ElMessage.info('甘特图放大功能开发中...')
}

const zoomOut = () => {
  // 甘特图缩小逻辑
  ElMessage.info('甘特图缩小功能开发中...')
}

const resetZoom = () => {
  // 甘特图重置逻辑
  ElMessage.info('甘特图重置功能开发中...')
}

const initGanttChart = () => {
  if (!ganttChart.value) return
  
  const chart = echarts.init(ganttChart.value)
  
  // 准备甘特图数据
  const tasks = flatTasks.value.map(task => ({
    name: task.name,
    value: [
      task.name,
      new Date(task.startDate).getTime(),
      new Date(task.endDate).getTime(),
      task.progress
    ],
    itemStyle: {
      color: task.status === '已完成' ? '#67C23A' : 
             task.status === '进行中' ? '#E6A23C' : '#909399'
    }
  }))
  
  const option = {
    title: {
      text: '项目甘特图',
      left: 'center'
    },
    tooltip: {
      formatter: function(params) {
        const start = new Date(params.value[1]).toLocaleDateString()
        const end = new Date(params.value[2]).toLocaleDateString()
        const progress = params.value[3]
        return `${params.value[0]}<br/>开始: ${start}<br/>结束: ${end}<br/>进度: ${progress}%`
      }
    },
    grid: {
      left: '15%',
      right: '10%',
      top: '10%',
      bottom: '10%'
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: function(value) {
          return new Date(value).toLocaleDateString()
        }
      }
    },
    yAxis: {
      type: 'category',
      data: tasks.map(task => task.name)
    },
    series: [{
      type: 'custom',
      renderItem: function(params, api) {
        const categoryIndex = api.value(0)
        const start = api.coord([api.value(1), categoryIndex])
        const end = api.coord([api.value(2), categoryIndex])
        const height = api.size([0, 1])[1] * 0.6
        
        return {
          type: 'rect',
          shape: {
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
          },
          style: api.style()
        }
      },
      data: tasks
    }]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const savePlan = async () => {
  try {
    // 这里应该调用API保存项目计划
    ElMessage.success('项目计划保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const exportPlan = () => {
  // 导出项目计划逻辑
  ElMessage.info('导出功能开发中...')
}

const exportMilestones = () => {
  // 导出里程碑逻辑
  ElMessage.info('导出功能开发中...')
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initGanttChart()
  })
})
</script>

<style scoped>
.project-planning {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.project-info-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.project-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-item .value {
  color: #303133;
}

.main-content {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.wbs-container,
.gantt-container,
.milestone-container,
.dependency-container {
  padding: 20px;
}

.wbs-toolbar,
.gantt-toolbar,
.milestone-toolbar,
.dependency-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.gantt-chart {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-planning {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .project-info {
    grid-template-columns: 1fr;
  }
  
  .wbs-toolbar,
  .gantt-toolbar,
  .milestone-toolbar,
  .dependency-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-right {
    justify-content: center;
  }
}
</style>